package com.jf3q.security.component;

import com.jf3q.common.utils.JwtTokenUtil;
import com.jf3q.security.service.impl.EduAclUserServiceImpl;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

public class JwtAuthencationTokenFilter extends OncePerRequestFilter {

	@Autowired
	private EduAclUserServiceImpl userInfoServie;
	@Autowired
	JwtTokenUtil jwtTokenUtil;
	@Value("${jwt.tokenHeader}")
	private String tokenHeader;
	@Value("${jwt.tokenHead}")
	private String tokenHead;

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
		String authToken = request.getHeader(tokenHeader);
		//存在token
		if (null != authToken && authToken.startsWith(tokenHead)) {

			String token = authToken.substring(tokenHead.length());

			String username = jwtTokenUtil.getUserNameFromToken(token);

			UserDetails userDetails = userInfoServie.loadUserByUsername(username);
			//验证token是否有效，重新设置用户对象
			if (jwtTokenUtil.validateToken(token)) {
				UsernamePasswordAuthenticationToken authenticationToken =
						new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
				SecurityContextHolder.getContext().setAuthentication(authenticationToken);
			}

		}
		filterChain.doFilter(request, response);

	}
}
